package com.lm.scau.dyb.db.Dalx;

import android.content.ContentValues;
import android.database.Cursor;

import com.lm.scau.dyb.activity.base.BaseActivity;
import com.lm.scau.dyb.bean.MovieType;
import com.lm.scau.dyb.db.DybDB;
import com.lm.scau.dyb.utils.FlagHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/20.
 */
public class MovieTypeDalx extends BaseDalx {
    private static final String TB_NAME = "tb_type";
    private static final String TY_ID = "ty_id";
    private static final String TY_URL = "ty_url";
    private static final String TY_TYPE = "ty_type";
    private static final String TY_TIME = "ty_time";

    public MovieTypeDalx(BaseActivity activity) {
        if (db == null) {
            db = DybDB.get(activity);
        }
        if (!db.tabbleIsExist(TB_NAME)) {
            createDataFileTable();
        }
    }

    private void createDataFileTable() {
        String createTableSql = "CREATE TABLE IF NOT EXISTS " + TB_NAME + "(" + TY_ID
                + " varchar, " + TY_URL + " varchar, " + TY_TYPE + " varchar, " + TY_TIME + " varchar)";
        db.creatTable(createTableSql);
    }

    /**
     * 获取最新的轮播时间，用来更新最新数据
     *
     * @return
     */
    @Override
    public String getLatelyTime() {
        String sql = "select " + TY_TIME + " from " + TB_NAME +
                " order by " + TY_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"1"});
        String time = "1970-01-01 00:00:00";

        while (cursor.moveToNext()) {
            time = cursor.getString(cursor.getColumnIndex(TY_TIME));
            break;
        }
        return time;
    }

    /**
     * 新增轮播数据
     *
     * @param movieType
     * @return
     */
    public boolean addMovieTypes(MovieType movieType) {
        boolean isOk = false;
        ContentValues values = new ContentValues();
        values.put(TY_ID, movieType.getTyID());
        values.put(TY_URL, movieType.getUrl());
        values.put(TY_TIME, movieType.getTime());
        values.put(TY_TYPE, movieType.getTyType());
        if (db.save(TB_NAME, values)) {
            isOk = true;
        }
        return isOk;
    }

    public List<String> getUrls() {
        List<String> urls = new ArrayList<>();
        String sql = "select " + TY_URL + "," + TY_TYPE + " from " + TB_NAME +
                " order by " + TY_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"10000"});
        while (cursor.moveToNext()) {
            String url = FlagHelper.CATEGOTY_DIR + cursor.getString(cursor.getColumnIndex(TY_URL));
            String type = cursor.getString(cursor.getColumnIndex(TY_TYPE));
            urls.add(url + "," + type);
        }
        return urls;
    }
}
